package com.orm.mybatis.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.orm.mybatis.entity.User;
import com.orm.mybatis.serviceImpl.UserServiceImpl;
import com.orm.mybatis.entity.ReturnData;
import com.orm.mybatis.entity.ReturnWithNoData;
import com.orm.mybatis.mapper.UserMapper;
import com.orm.mybatis.utils.MD5Util;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserServiceImpl userService;

    @GetMapping(value = "/get/all")
    public Object getAllUser(){
        PageInfo pageInfo =  userService.findAllUser();
        return ReturnData.success(pageInfo);
    }

    @GetMapping(value = "/get/{id}")
    public Object getUserById(@PathVariable("id") Long id){
        User list =  userService.findUserById(id);
        return ReturnData.success(list);
    }

    @Transactional("localMysqlTransactionManager")
    @PostMapping(value = "/insert/user",produces = {"application/json;charset=UTF-8"})
    public Object insertUser(@RequestBody String json){
        JSONObject jsonObject = JSONObject.parseObject(json);
        User user = JSON.toJavaObject(jsonObject,User.class);
        userService.insertUser(user);
        System.out.println("user.getId():      "+user.getId());
        userService.insertUserWithoutXml(user);
        System.out.println("user.getId():      "+user.getId());
    return ReturnWithNoData.builder().rv(200).msg("success").build();
    }

    @Transactional("localMysqlTransactionManager")
    @PostMapping(value = "/insert",produces = {"application/json;charset=UTF-8"})
    public Object insertUser1() throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date =  simpleDateFormat.format(new Date());
        User user = User.builder().email("andrew@qq.com").name("andrew").password("123456").phoneNumber("123")
                .lastUpdateTime(date).createTime(date).status(0).salt(MD5Util.createSaltValue()).build();
//        userMapper.saveUser(user);
//        userService.test();
        try {
            userService.testNoXml();
        }finally {
            System.out.println("finaaly");
        }
        System.out.println("可以看到吗");


        return ReturnWithNoData.success();
    }

}
